package com.nutstudy.mybatis.org.mybatis.spring;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

/**
 * @author: HyoJoo-W
 * @date: 2021-08-28 13:36
 * @description:
 */

public class NutFactoryBean implements FactoryBean
{
    private Class mapperClass;

    private SqlSession sqlSession;

    @Autowired
    public void setSqlSession(SqlSessionFactory sqlSessionFactory)
    {
        sqlSessionFactory.getConfiguration().addMapper(mapperClass);
        this.sqlSession = sqlSessionFactory.openSession();
    }

    public NutFactoryBean(Class mapperClass)
    {
        this.mapperClass = mapperClass;
    }

    @Override
    public Object getObject() throws Exception
    {
//        Object instance = Proxy.newProxyInstance(NutFactoryBean.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler()
//        {
//            @Override
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
//            {
//                System.out.println(method.getName());
//                return null;
//            }
//        });
//
//        return instance;

        return this.sqlSession.getMapper(mapperClass);
    }

    @Override
    public Class<?> getObjectType()
    {
        return this.mapperClass;
    }
}
